<!--
* description: 上传附件
* author: dxuem
* createdDate:
* modify：2019-11-07 添加上传文件按钮，submitBtn动态控制是否显示
                     将span，是否显示文件列表（show-file-list）设为动态属性
                     通过change触发，将文件列表发送给页面
-->
<template>
  <el-col :span="span" :class="{'crm-label-required':isRequire}">
    <el-form-item :label="labelName">
      <el-upload
        class="upload-demo-crm upload-demo"
        ref="upload"
        :action="action"
        :accept="accepttype"
        :multiple="ismutiple"
        :on-change="change"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :auto-upload="isautoupload"
        :file-list="fileList"
        :show-file-list="isShowList"
        :limit="limit"
        :on-exceed="handleExceed"
        :http-request="handleChange"
        :beforeUpload="beforeAvatarUpload"
      >
        <el-button slot="trigger" size="small" type="primary" ref="btn">{{buttonText}}</el-button>
        <!-- <el-button
          v-show="submitBtn"
          style="margin-left: 10px;"
          size="small"
          type="primary"
          @click="submitUpload"
        >{{upText}}</el-button> -->
      </el-upload>
    </el-form-item>
  </el-col>
</template>

<script>
export default {
  name: "UpLoad",
  props: {
    buttonText: { type: String, default: "选择文件" },
    labelName: { type: String, default: "" },
    fileList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    getVal: {
      type: Array,
      default: function() {
        return [];
      }
    },
    textField: { type: String, default: "" },
    codeField: { type: String, default: "" },
    submitBtn: { type: Boolean, default: true }, //是否显示上传文件按钮
    isShowList: { type: Boolean, default: true }, //是否显示文件列表
    upText: { type: String, default: "上传文件" }, //按钮文字
    action: { type: String, default: "" }, //文件上传地址
    accepttype: { type: String, default: "" }, //文件类型限制
    ismutiple: { type: Boolean, default: true }, //是否可多选
    ismore: { type: Boolean, default: true }, //是否可上传多个文件
    limit: { type: Number, default: 10 }, //文件个数限制
    fileSize: { type: Number, default: 10 },
    span: { type: Number, default: 6 },
    isautoupload: { type: Boolean, default: false }, //是否自动上传
    initList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    isRequire:{ type: Boolean, default: false },
  },
  data() {
    return {
      category: "crm",
      imgUrl: "",
      // accfiles: this.accepttype
      filess: []
    };
  },
  watch: {
    getVal(list) {
      this.fileList=list
      // this.filess=list
    }
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    // choose:function(){
    //   let that =this;
    //   this.father.input=this.$refs.btn.value;
    //   that.input=this.
    // },
    handlePreview(file) {
      console.log(file)
      debugger
      if (file.path) {
        let url = file.path;
        window.open(url);
      }
      else {
        let url = file.raw.path;
        window.open(url);
      }
    },
    //如果只能上传一个文件，后面选的覆盖前面的
    change(files, list) {
      if (!this.ismore) {
        if (list.length > 1) {
          this.fileList = [];
          this.fileList.push(files);
        }
      } else {
        //this.fileList = list;
      }
      // let getFiles = [];
      // for (let i = 0; i < list.length; i++) {
      //   for (let j = 0; j < this.filess.length; j++) {
      //     if (list[i].name == this.filess[j].name) {
      //       getFiles.push(this.filess[j]);
      //     }
      //   }
      // }
      // this.filess = getFiles;
      // console.log(getFiles);
      // this.$emit("emitCode", getFiles); //将文件列表发送给页面，可在输入框进行显示
    },
    // 超出限制个数
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择个文件${this.limit}，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    /**
     * 上传请求封装.
     * 1上传附件（类型？:xls,xlsx）
     * 2上传证件图片(类型：jpg、jpeg、png)
     *
     */
    handleChange(param) {
      const that = this;
      debugger
      var fileType = param.file.name.substring(
        param.file.name.lastIndexOf(".") + 1
      );
      //类型不要写死
      // const extension3 = fileType === "jpg";
      // const extension4 = fileType === "jpeg";
      // const extension5 = fileType === "png";
      // const isLt2M = file.size / 1024 / 1024 < 10

      // if (!(extension3 || extension4 || extension5)) {
      //   this.$message({
      //     message: "上传文件只能是 jpg、jpeg、png格式!",
      //     type: "warning"
      //   });
      //   return;
      // } else {
      // MP上传url
      const url = "/mp/file/" + that.category + "/upload.do";
      that
        .$requestUpload(url, param)
        .then(response => {
          that.imgUrl = "";
          let code = "";
          let name = "";
          if (
            response.result === "1" &&
            response.path.length > 0 &&
            response.path[0].length > 0 &&
            response.path[0][0].indexOf("|") > -1
          ) {
            // this.$message({
            //   type: "success",
            //   message: "上传成功!"
            // });
            // 返回格式：[["xxxx.png|/upload/{category}/{yyyyMMdd}/{guid}/xxxx.jpg","xxx.xx KB"]]
            // 截取出/upload/{category}/{yyyyMMdd}/{guid}/xxxx.jpg返回
            that.imgUrl = response.path[0][0].split("|")[1];
            name = response.path[0][0].split("|")[0];
            code = that.imgUrl;
            for(var i=0;i<that.fileList.length;i++){
              if(that.fileList[i].name==name){
                that.fileList[i].path=code
              }
            }
            param.file.path=code
            this.filess.push({ name: name, path: code });
            // this.fileList=this.filess
            // this.fileList.push({ name: name, path: code });
            console.log(this.fileList);
            that.$emit("emitCode", this.filess);
          }
          // this.filess.push({ name: name, path: code });
          // console.log(this.filess);
          // that.$emit("emitCode", this.filess);
          // 邮件发送 附件
          //   var parent = this.$utils.getHasFormFieldParentComponent(this);
          //   if(parent.form.accessory){
          //     parent.form.accessory.push(name)
          //   }
        })
        .catch(err => {
          that.modeCode = "";
          console.info(err);
        });
      // }
    },
    handleRemove(file, fileList) {
      // let getFiles = [];
      // for (let j = 0; j < this.filess.length; j++) {
      //   if (file.name === this.filess[j].name) {
      //   } else {
      //     getFiles.push(this.filess[j]);
      //   }
      // }
      // this.filess = getFiles;
      // console.log(getFiles);
      this.$emit("delFiles", fileList);
    },
    /**
     * 文件大小限制
     * 文件格式限制
     */
    beforeAvatarUpload(file) {
      let that = this;
      //判断是否符合    设定文件大小（fileSize，单位是M）
      if (file.name != null) {
        //大小
        if (file.size / 1024 / 1024 > that.fileSize) {
          this.$message({
            message: file.name + "上传文件不能超过" + that.fileSize + "M！",
            type: "warning"
          });
        }

        //格式 dxm已做
        // var flag = 1;
        // for (let i = 0; i < that.fileType.length; i++) {
        //   debugger;
        //   if (
        //     that.fileType[i] ===
        //     file.name.substring(file.name.lastIndexOf(".") + 1)
        //   ) {
        //     flag++;
        //   } else {
        //     flag = flag;
        //   }
        // }
        // if (flag == 1) {
        //   this.$message({
        //     message: "上传文件格式不正确！",
        //     type: "warning"
        //   });
        //   return;
        // }
      }
    }
    // setInputWidth(span){
    //   switch(span){
    //     case 6:return '';
    //     case 12:return 'width:85%;line-height: 38px;';
    //     case 8 :return 'width:68%;line-height: 38px;'
    //   }
    // }
  }
};
</script>
<style scoped>
/* .upload-demo-crm .el-upload-list .el-upload-list--text {
  position: absolute;
  float: left;
}
.el-button {
  float: right;
} */
</style>
